<template>
  <div class="app-container" v-loading="loading">
    <el-form :model="formData" :rules="rules" ref="validateForm" label-width="140px">
      <el-form-item label="项目名称" prop="name">
        <el-input v-model="formData.name"></el-input>
      </el-form-item>
      <el-form-item label="项目地点" prop="addr">
        <el-input v-model="formData.addr"></el-input>
      </el-form-item>
      <el-form-item label="路由（SEO）" prop="route">
        <el-input v-model="formData.route"></el-input>
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <el-select v-model="formData.category" placeholder="请选择">
          <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="封面图片" prop="pic">
        <upload :limit="1" v-model="formData.pic" ref="upload" :multiple="false"></upload>
      </el-form-item>
      <el-form-item label="项目图片" prop="atlas">
        <upload :limit="999" v-model="formData.atlas"></upload>
      </el-form-item>
      <el-form-item label="首页推荐" prop="status">
        <el-switch v-model="formData.recommend"></el-switch>
        {{ formData.recommend ? '开启' : '停用' }}
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-switch v-model="formData.status"></el-switch>
        {{ formData.status ? '开启' : '停用' }}
      </el-form-item>

      <el-form-item label="简介" prop="intro">
        <el-input v-model="formData.intro"></el-input>
      </el-form-item>
      <el-form-item label="展现形式" prop="viewMode">
        <el-radio-group v-model="formData.extendData.viewMode">
          <el-radio :label="1">画廊</el-radio>
          <el-radio :label="2" disabled>瀑布流</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="详情" prop="content">
        <!-- <ckeditor :editor="editor" v-model="formData.content" :config="editorConfig" @ready="MyCustomUploadAdapterPlugin">
        </ckeditor> -->
        <tinymce v-model="formData.content" :height="300" />
      </el-form-item>
    </el-form>
    <div style="height: 20px;"></div>
    <div class="fixed--footer">
      <el-button type="primary" id="editor" @click="submitForm('validateForm')">提交</el-button>
      <el-button @click="resetForm('validateForm')">重置</el-button>
    </div>
  </div>
</template>
<script>
import { config } from '../config'
import { getDetail, create, update } from '@/api/product'
import { fetchList } from '@/api/product-category'
import { baseApi } from '@/utils'
import Tinymce from "@/components/Tinymce";
import ClassicEditor from '@givebest/ckeditor5-custom-build'
import '@givebest/ckeditor5-custom-build/build/translations/zh-cn.js'
import MyUploadAdapter from '@/utils/ckeditor/uploadImg';
import Upload from "@/components/Global/Upload"
import { getToken } from '@/utils/auth'
const token = getToken()
const Authorization = `Bearer ${token}`
const { routePath } = config
export default {
  name: 'ProductCreateUpdate',
  components: { Upload, Tinymce },
  filters: {},
  props: {
    type: {
      type: String,
      default: function () {
        return 'create'
      },
    },
  },
  data() {
    return {
      loading: false,
      querys: {
        id: '',
      },
      formData: {
        id: '',
        name: '',
        route: '',
        category: '',
        pic: '',
        atlas: '',
        recommend: false,
        intro: '',
        content: '',
        status: true,
        addr: '',
        extendData: {
          viewMode: 1
        }
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          {
            min: 1,
            max: 100,
            message: '长度在 1 到 100 个字符',
            trigger: 'blur',
          },
        ],
        addr: [
          { required: false, message: '请输入项目地点', trigger: 'blur' },
        ],
        category: [
          {
            required: true,
            message: '请选择分类',
            trigger: 'change',
          },
        ],
        pic: [
          {
            required: true,
            message: '请上传封面图片',
            trigger: 'change',
          },
        ],
        // content: [{ required: true, message: '请输入详情', trigger: 'change' }],
      },
      categoryList: [],
      // 文件上传
      uploadHeaders: {
        Authorization,
      },
      // 编辑器
      editor: ClassicEditor,
      editorConfig: {
        toolbar: {
          shouldNotGroupWhenFull: false,
          items: [
            'heading',
            'blockQuote',
            '|',
            'bold',
            'underline',
            'italic',
            'highlight',
            '|',
            'strikethrough',
            'code',
            'subscript',
            'superscript',
            'removeFormat',
            '|',
            'fontColor',
            'fontSize',
            'fontFamily',
            'fontBackgroundColor',
            'findAndReplace',
            '|',
            'alignment',
            'indent',
            'outdent',
            'bulletedList',
            'numberedList',
            '|',
            'imageUpload',
            'imageInsert',
            'insertTable',
            'mediaEmbed',
            '|',
            'specialCharacters',
            'horizontalLine',
            'link',
            '|',
            'undo',
            'redo'
          ]
        },
        language: 'zh-cn',
        image: {
          toolbar: [
            'imageTextAlternative',
            'imageStyle:inline',
            'imageStyle:block',
            'imageStyle:side',
          ],
        },
        table: {
          contentToolbar: ['tableColumn', 'tableRow', 'mergeTableCells'],
        },
        fontFamily: {
          options: [
            'default',
            '宋体,SimSun',
            '新宋体,NSimSun',
            '黑体,SimHei',
            '微软雅黑,Microsoft YaHei',
            '楷体,KaiTi GB2312',
            '隶书,LiSu',
            '幼园,YouYuan',
            '华文细黑,STXihei',
            '细明体,MingLiu',
            '新细明体,PMingLiU'
          ]
        },
        fontSize: {
          options: [
            'default',
            '12px',
            '13px',
            '14px',
            '15px',
            '16px',
            '19px',
            '22px',
            '24px',
            '29px',
            '32px',
            '40px',
            '48px'
          ]
        },
        simpleUpload: {
          uploadUrl: `${baseApi}/upload`,
          withCredentials: true,
          headers: {
            Authorization,
          },
        },
      },
    }
  },
  created() {
    this.getQuery()
    this.getCategoryList()
  },
  methods: {
    MyCustomUploadAdapterPlugin(editor) {
      editor.plugins.get('FileRepository').createUploadAdapter = (loader) => {
        return new MyUploadAdapter(loader);
      };
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          return false
        }
        this.loading = true
        if (this.type === 'update') {
          this.putUpdate()
        } else {
          this.postCreate()
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 获取  query 参数
    getQuery() {
      const querys = this.$route.query || {}
      this.querys = querys
      if (this.type === 'update') {
        if (!querys.id) {
          this.$router.push('list')
          return
        }
        this.getDetail()
      }
    },
    // 清空分类选择
    onResetCategory() {
      this.formData.category = []
    },
    // 添加
    postCreate() {
      create(this.formData).then(() => {
        this.loading = false

        this.$message({
          message: '操作成功',
          type: 'success',
          duration: 600,
        })

        setTimeout(() => {
          this.$router.push(`${routePath}list`)
        }, 300)
      })
    },
    // 更新
    putUpdate() {
      update(this.formData).then(() => {
        this.loading = false
        this.$message({
          message: '操作成功',
          type: 'success',
          duration: 600,
        })
        setTimeout(() => {
          this.$router.push(`${routePath}list`)
        }, 300)
      })
    },
    // 详情
    getDetail() {
      this.loading = true
      getDetail(this.querys.id).then((res) => {
        this.loading = false
        this.formData = res
      })
    },
    // 分类列表
    getCategoryList() {
      fetchList().then((res) => {
        this.categoryList = res.data || []
      })
    },
  },
}
</script>
